package io.elegant.widgets

import android.os.Build
import android.view.ViewGroup
import android.widget.ProgressBar
import androidx.annotation.RequiresApi
import com.google.protobuf.Any
import io.elegant.sessions.BaseSession
import io.elegant.toAny
import io.elegant.toIntValue
import kotlinx.coroutines.CoroutineScope
import kotlin.reflect.KClass

class ProgressBarWidget<T: ProgressBar>(
    private val session: BaseSession,
    private val group: ViewGroup,
    cs: CoroutineScope
): BaseWidget<T>(session, group, cs) {
    override fun createView(clazz: KClass<T>, vararg argv: Any): T {
        return clazz
            .constructors
            .first { it.parameters.size == 3 }
            .call(group.context, null, android.R.style.Widget_DeviceDefault_ProgressBar_Horizontal)
    }
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onReceive(name: String, sessionId: Long, futureId: Long, vararg argv: Any): Boolean {
        if (when(name) {
                "getRange" -> getRange(sessionId, futureId)
                "setRange" -> setRange(*argv)
                "getValue" -> getValue(sessionId, futureId)
                "setValue" -> setValue(*argv)
                else -> null
        } != null)
            return true
        return super.onReceive(name, sessionId, futureId, *argv)
    }
    @RequiresApi(Build.VERSION_CODES.O)
    private fun getRange(sessionId: Long, futureId: Long) = view?.let {
        onGetRange(it.min.toAny(), it.max.toAny(), sessionId, futureId)
    }?.let {  }
    private fun onGetRange(min: Any, max: Any, sessionId: Long, futureId: Long) = session.apply {
        sendAction("onGetRange", sessionId, futureId, min, max)
    }
    @RequiresApi(Build.VERSION_CODES.O)
    private fun setRange(vararg argv: Any) = view?.let {
        it.min = argv[0].toIntValue()
        it.max = argv[1].toIntValue()
    }
    private fun getValue(sessionId: Long, futureId: Long) = view?.let {
        onGetValue(it.progress.toAny(), sessionId, futureId)
    }.let {  }
    private fun onGetValue(value: Any, sessionId: Long, futureId: Long) = session.apply {
        sendAction("onGetValue", sessionId, futureId, value)
    }
    private fun setValue(vararg argv: Any) = view?.let {
        it.progress = argv[0].toIntValue()
    }
}